package api

import (
	"github.com/gin-gonic/gin"
	"guard/internal/app/admin/models"
	"guard/internal/conf"
	"guard/internal/errors"
	"guard/internal/result"
	"guard/internal/tool"
	"net/http"
)

// 注册客户端
func registerClient(c *gin.Context) {

	var cInfo = struct {
		ClientId     string `json:"client_id"`
		ClientName   string `json:"client_name,omitempty" binding:"required"`
		RedirectUris string `json:"redirect_uris,omitempty" binding:"required"`
	}{}

	err := c.ShouldBindJSON(&cInfo)
	if err != nil {
		_ = c.Error(errors.OtherError("错误的请求类型"))
		return
	}

	// 判断当前app_name是否符合标准
	if !tool.VerificationParam(tool.ClientNameReg, cInfo.ClientName) || !tool.VerificationParam(tool.ClientRedirectUrlReg, cInfo.RedirectUris) {
		_ = c.Error(errors.OtherError("app名称，重定向地址不规范"))
		return
	}

	// 获取登录用户
	username := c.GetString(conf.Conf.Cache.LoginUserKey)

	mci := models.ClientInfo{}
	if cInfo.ClientId != "" {
		mci.ClientId = cInfo.ClientId
	}
	mci.ClientName = cInfo.ClientName
	mci.RedirectUris = cInfo.RedirectUris

	err = adminService.RegisterClient(username, &mci)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: http.StatusOK,
		Msg:  "客户端记录成功",
		Data: nil,
	})
}

// 查询用户注册的所有客户端
func applyClient(c *gin.Context) {

	// 获取登录用户
	username := c.GetString(conf.Conf.Cache.LoginUserKey)

	appAll, err := adminService.UserAppAll(username)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: appAll,
	})
}

// 删除客户端
func delClient(c *gin.Context) {

	cid := struct {
		ClientId string `json:"client_id,omitempty" binding:"required"`
	}{}

	err := c.ShouldBindJSON(&cid)
	if err != nil {
		_ = c.Error(errors.OtherError("错误的clientId"))
		return
	}

	// 获取登录用户
	username := c.GetString(conf.Conf.Cache.LoginUserKey)

	err = adminService.RemoveUserApp(username, cid.ClientId)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: http.StatusOK,
		Msg:  "删除成功",
		Data: nil,
	})
}
